<?php


namespace App\Http\service;
use App\Exceptions\ApiException;
use App\Models\Sys;
use Illuminate\Support\Facades\Log;
use OSS\OssClient;
use function app\Utils\go;

class OssService
{
    /* 城市名称：
        *
        *  经典网络:下可选：杭州、上海、青岛、北京、张家口、深圳、香港、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
        *  VPC: 网络下可选：杭州、上海、青岛、北京、张家口、深圳、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
        */
    private $city = '杭州';
    private $ossClient ;
    // 经典网络 or VPC
    private $networkType = '经典网络';
    private $AccessKeyId = 'LTAI5tAZJa4t4LjXn1GaC1uF';
    private $AccessKeySecret = 'sZorCh5lmycZ9fFfD2qc2DDKEWJpjt';
    private $bucketName;
    private $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";


    /**
     * 私有初始化 API，非 API，不用关注
     *
     * OSS constructor.
     * @param bool $isInternal 是否使用内网
     * @param mixed $city
     * @throws Exception
     */
    public function __construct($city = '杭州', $isInternal = false)
    {
        if ($this->networkType == 'VPC' && !$isInternal) {
            throw new ApiException("VPC 网络下不提供外网上传、下载等功能");
        }
        $this->city = $city;
        $this->AccessKeyId=Sys::getValue("ali_AccessKeyId");
        $this->AccessKeySecret=Sys::getValue("ali_AccessKeySecret");
        $this->bucketName=Sys::getValue("bucket_name");
        try {
            $this->ossClient=new OssClient($this->AccessKeyId,$this->AccessKeySecret,$this->endpoint);
        }catch (\Exception $exception){
            Log::error($exception->getMessage());
        }
    }

    public  function uploadFile($object,$filePath)
    {
        $options = array(
            OssClient::OSS_HEADERS => array(
                'x-oss-object-acl' => OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE,
            ),
        );
        try {
           $res=$this->ossClient->uploadFile($this->bucketName,$object,$filePath,$options);
           Log::error($res);
         //  $res=$this->ossClient->putBucketAcl($this->bucketName,OssClient::OSS_ACL_TYPE_PUBLIC_READ);
        }catch (\Exception $exception){
            Log::error($exception->getMessage());
        }
    }

    public function delFile($object)
    {
        try {
            $res=$this->ossClient->deleteObject($this->bucketName,$object);
            return $res;
        }catch (\Exception $exception){
            Log::error($exception->getMessage());
        }
    }

   private function base64EncodeImage ($image_file) {

        $base64_image = '';

        $image_info = getimagesize($image_file);

        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));

        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));

        return $base64_image;

    }



}
